package com.tc.property.config.zk;

import com.tc.property.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;
import java.util.regex.Pattern;

public class CfgCenterUtils {

	private static Logger log = LoggerFactory.getLogger(CfgCenterUtils.class);

	public static List<String> getLocalIp() {
		List<String> ipList = new ArrayList<String>();
		
		try {
			Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
			NetworkInterface networkInterface;
			Enumeration<InetAddress> inetAddresses;
			InetAddress inetAddress;
			String ip;
			while (networkInterfaces.hasMoreElements()) {
				networkInterface = networkInterfaces.nextElement();
				inetAddresses = networkInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					inetAddress = inetAddresses.nextElement();
					if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
						ip = inetAddress.getHostAddress();
						ipList.add(ip);
					}
				}
			}
		} catch (SocketException e) {
			log.error("getLocalIp:" + e.getMessage());
		}
		
		return ipList;
	}
	
	public static List<String> getLocalPool(){
		List<String> poolList = new ArrayList<String>();
		String pool = Utils.getSysProps().getProperty("VIP_POOL_NAME");
		if(StringUtils.isBlank(pool)){
			pool = Utils.getSysProps().getProperty("VIP_POOL_NAME".toLowerCase());
		}
		if(StringUtils.isNoneBlank(pool)){
			poolList = Arrays.asList(pool.split(","));
		}
		return poolList;
	}

	public static boolean isContains(String ips, List<String> ipList) {
		for (String localIp : ipList) {
			if (StringUtils.contains(ips, localIp)) {
				return true;
			}
		}
		return false;
	}
	
	public static boolean isContainsLocalPool(String pools, List<String> localPools){
		for (String localPool : localPools) {
			for (String pool : pools.split(",")) {
				if (pool.equalsIgnoreCase(localPool)) {
					return true;
				}
			}
		}
		return false;
	}

	public static boolean isMatcher(Pattern pattern, List<String> ipList) {
		for (String localIp : ipList) {
			if (pattern.matcher(localIp).matches()) {
				return true;
			}
		}
		return false;
	}

	public static String getParentZkPath(final String zkPath) {
		int lastindex = zkPath.lastIndexOf("/");
		return zkPath.substring(0, lastindex);
	}

}
